<template>
  <div class="AddOrUpdate_main add_container column_three">
    <el-tabs v-model="activeName">
      <el-tab-pane label="设备维修" name="first">
        <div class="main_main">
          <el-form ref="form" :model="formData" :rules="rules" :inline="true">
            <el-form-item label="维修单号" prop="code">
              <CodeRuleInput :band-value.sync="formData.code" table-name="device_repair_library" column-name="code" :is-edit="id" />
            </el-form-item>
            <el-form-item label="故障类型" prop="malfunctionTypeName" class="clickChoose">
              <el-input v-model="formData.malfunctionTypeName" placeholder="请选择" readonly />
              <!--              <el-select v-model="formData.typeId" filterable clearable placeholder="请选择">-->
              <!--                <el-option-->
              <!--                  v-for="item in userOptions"-->
              <!--                  :key="item.id"-->
              <!--                  :label="item.name"-->
              <!--                  :value="item.id"-->
              <!--                />-->
              <!--              </el-select>-->
              <a class="clickChoose_button" @click.prevent="addType">
                <svg-icon icon-class="选择弹框" />
              </a>
            </el-form-item>
            <el-form-item label="维修类型" prop="applyDevice">
              <el-select v-model="formData.repairOption" filterable clearable placeholder="请选择" @change="maintainType">
                <el-option
                  v-for="item in repairOption"
                  :key="item.id"
                  :label="item.repairOptionName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="维修厂商" prop="firmId">
              <el-select v-model="formData.firmId" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in userOptions2"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="维修费用(元)" prop="cost" class="cost">
              <el-input-number
                ref="refNumber"
                v-model="formData.cost"
                placeholder="请输入"
                controls-position="right"
                :min="0"
                :max="10000000"
                clearable
              />
            </el-form-item>
            <el-form-item label="维修时长(h)" prop="duration">
              <el-input v-model="formData.duration" type="number" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item v-if="!this.isEdit" label="维修完成时间" prop="completeTime">
              <el-date-picker
                v-model="formData.completeTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                :editable="false"
              />
            </el-form-item>
            <el-form-item label="维修图片" class="double">
              <FileManageFull
                :file-names="formData.fileName"
                :file-real-names="formData.fileRealName"
                :file-urls="formData.fileUrl"
                :row-index="1"
                @fileName="setFileName2"
              />
            </el-form-item>
            <el-form-item label="维修纪要" class="double">
              <el-input v-model="formData.description" maxlength="200" show-word-limit type="textarea" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="临时处理对策" class="double">
              <el-input v-model="formData.tempSolution" maxlength="200" show-word-limit type="textarea" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="长期改善对策" class="double">
              <el-input v-model="formData.longTermSolution" maxlength="200" show-word-limit type="textarea" placeholder="请输入" />
            </el-form-item>

            <div class="formItem_header">
              <div class="formItem_header_operate">
                <a class="formItem_header_operate_item" @click="addRecord">
                  <svg-icon icon-class="新增" />
                  <div class="item_name">添加</div>
                </a>
                <a class="formItem_header_operate_item" @click="importSpareParts">
                  <svg-icon icon-class="导入" />
                  <div class="item_name">导入</div>
                </a>
                <a class="formItem_header_operate_item delete" @click="remove1">
                  <svg-icon icon-class="删除" />
                  <div class="item_name">删除</div>
                </a>
              </div>
            </div>
            <div ref="table_container2" class="table_container">
              <el-table
                ref="table"
                :data="tableData"
                :height="tableHeight"
                stripe
                border
                :header-cell-class-name="headerCellClassName"
                @selection-change="selectionChange1"
              >
                <el-table-column type="selection" align="center" width="50" />
                <el-table-column
                  prop="spareCode"
                  label="备件编码"
                  min-width="120"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  prop="spareName"
                  label="备件名称"
                  min-width="100"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  prop="spareModel"
                  label="规格型号"
                  min-width="100"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  prop="numberUnitLabel"
                  label="备件单位"
                  min-width="100"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  prop="deviceSpareWarehouseName"
                  label="仓库"
                  min-width="100"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  prop="batch"
                  min-width="100"
                  label="批号"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  prop="inventoryNumber"
                  label="库存数量"
                  :min-width="SETTINGS.settings_decimalDigits_length"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  fixed="right"
                  prop="number"
                  label="使用数量"
                  :min-width="SETTINGS.settings_decimalDigits_length"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.useNumber" style="" placeholder="请输入" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="设备信息" name="second" :data="formatDate1">
        <div class="main_main">
          <el-form ref="form1" :model="formatDate1" :rules="rules" :inline="true">
            <el-form-item label="设备编码" prop="code">
              <el-input v-model="formatDate1.code" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="formatDate1.name" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="设备类型" prop="typeName">
              <el-input v-model="formatDate1.typeName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="规格型号" prop="model">
              <el-input v-model="formatDate1.model" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="设备厂商" prop="firmName">
              <el-input v-model="formatDate1.firmName" placeholder="暂无" disabled />
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="报修信息" name="third" :data="formatDate2">
        <div class="main_main main_main_third">
          <el-form ref="form2" :model="formatDate2" :rules="rules" :inline="true">
            <el-form-item label="报修单号" prop="code" class="repairs">
              <el-input v-model="formatDate2.code" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="报修设备" prop="bookName">
              <el-input v-model="formatDate2.bookName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="设备状态" prop="deviceStatusLabel">
              <el-input v-model="formatDate2.deviceStatusLabel" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="设备故障时间" prop="planStartTime">
              <el-input v-model="formatDate2.malfunctionTime" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="期望修复时间" prop="planEndTime">
              <el-input v-model="formatDate2.planEndTime" placeholder="暂无" disabled />
            </el-form-item>
            <el-divider />
            <el-form-item label="故障类型" prop="typeName">
              <el-input v-model="formatDate2.typeName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="紧急程度" prop="emergencyDegreeLabel">
              <el-input v-model="formatDate2.emergencyDegreeName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="报修人员" prop="reportPersonName">
              <el-input v-model="formatDate2.reportPersonName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="故障情况拍照" class="double">
              <FileManageFull
                :file-names.sync="formatDate2.docName"
                :file-real-names.sync="formatDate2.docRealName"
                :file-urls.sync="formatDate2.docUrl"
                :readonly="true"
              />
            </el-form-item>
            <el-form-item label="附件" class="double">
              <FileManageFull
                :file-names.sync="formatDate2.fileName"
                :file-real-names.sync="formatDate2.fileRealName"
                :file-urls.sync="formatDate2.fileUrl"
                :readonly="true"
              />
            </el-form-item>
            <el-form-item label="故障现象" prop="phenomenon" class="double">
              <el-input v-model="formatDate2.phenomenon" type="textarea" placeholder="暂无" disabled />
            </el-form-item>
            <el-divider />
            <el-form-item label="维修人员" prop="repairPersonName">
              <el-input v-model="formatDate2.repairPersonName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="计划修复时间范围" prop="planEndTime" class="double">
              <el-input v-model="formatDate2.planTime" placeholder="暂无" disabled />
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button v-if="!isShow" @click.stop="onSubmit">保存</el-button>
      <el-button @click.stop="submit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getTypelist, getManagelist } from '@/api/equipmentManage/equipmentRepair/repairRecord'
import addRecord from '../../sparePartsManagement/sparePartsCollocation/chooseSpareParts.vue'
import addErrorType from '@/views/equipmentManage/equipmentRepair/errorType/addErrorType'
import ImportData from '@/components/JLink/common/ImportData'
import { importMethod } from '@/api/equipmentManage/sparePart/outWarehouse'
import moment from 'moment'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isEdit: {}
  },
  data() {
    const validateName = (rule, value, callback) => {
      callback()
    }
    const cost = (rule, value, callback) => {
      if (!this.SETTINGS.reg_zero.test(value)) {
        callback(new Error('维修费用未正确填写'))
      } else {
        callback()
      }
    }
    const duration = (rule, value, callback) => {
      if (value) {
        if (!this.SETTINGS.reg_integer.test(value)) {
          callback(new Error('维修时长只能为整数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const completeTime = (rule, value, callback) => {
      this.$refs.form.clearValidate('completeTime')
      if (!value) {
        callback(new Error('维修完成时间不能为空'))
      } else {
        callback()
      }
      if (value < this.formatDate2.malfunctionTime) {
        callback(new Error('维修完成时间不能小于设备故障时间'))
      } else {
        callback()
      }
    }
    return {
      pageId: '维修工单', // 页面唯一标识
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        roleIdsArray: undefined,
        roleIds: undefined,
        duration: undefined,
        repairTypeId: undefined,
        repairTypeCode: undefined,
        firmId: undefined,
        cost: undefined,
        description: undefined,
        tempSolution: undefined,
        longTermSolution: undefined,
        malfunctionTypeName: undefined,
        repairOption: undefined,
        repairOptionName: undefined,
        firmName: undefined,
        completeTime: '',
        typeId: 0,
        status: 1,
        isSubmit: '1',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        docName: '',
        docRealName: '',
        docUrl: '',
        data: []
      },
      num: 1,
      isSubmit: 1,
      roleOptions: [],
      activeName: 'first',
      tableData: [],
      tableHeight: '400',
      userOptions: [],
      userOptions2: [],
      formatDate1: [],
      formatDate2: [],
      selectionsAll1: [],
      nativeSelect: '',
      value: '',
      isShow: false,
      rules: {
        malfunctionTypeName: [
          { required: true, message: '故障类型不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '维修单号不能为空', trigger: 'blur' }
        ],
        completeTime: [
          { required: true, validator: completeTime, trigger: 'change' }
        ],
        name: [
          { required: true, validator: validateName, trigger: 'change' }
        ],
        typeName: [
          { required: true, validator: validateName, trigger: 'change' }
        ],
        bookName: [
          { required: true, validator: validateName, trigger: 'change' }
        ],
        cost: [
          { validator: cost, trigger: 'change' }
        ],
        duration: [
          { validator: duration, trigger: 'change' }
        ]
      },
      disabled: false,
      repairOption: [
        { repairOptionName: '自修', id: 0 },
        { repairOptionName: '委外', id: 1 }
      ]
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      if (this.$store.state.order.isEdit) {
        this.isEdit = this.$store.state.order.isEdit
        this.$store.state.order.isEdit = ''
      }
      this.isShow = true
      this.getInfo()
    }
    this.getList()
  },
  methods: {
    headerCellClassName(data) {
      if (['number'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(res.data).forEach(key => { // 给右边数据赋值
          this.formData = res.data[0]
          if (this.formData.malfunctionTypeName == null || '') {
            this.formData.malfunctionTypeName = undefined
          }
          if (this.formData.status !== 3) {
            this.isShow = false
          }
          this.tableData = res.data[1]
          this.formatDate1 = res.data[2]
          this.formatDate2 = res.data[3]
        })
        // if (this.formData.repairOption == 0 || this.formData.repairOption == null) {
        //   this.disabled = true
        //   this.formData.firmId = undefined
        //   this.formData.cost = undefined
        //   this.formData.repairOptionName = '自修'
        //   this.formData.repairOption = 0
        // } else {
        //   this.disabled = false
        // }
        if (!this.formData.duration) {
          this.formData.duration = undefined
        }
      })
    },
    getList() {
      getTypelist(
        { status: 1 }
      ).then(res => {
        this.userOptions = res.data
      })
      getManagelist(
        { status: 1 }
      ).then(res => {
        this.userOptions2 = res.data
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.id = this.id
          this.formData.roleIds = this.formData.roleIdsArray
          this.tableData.forEach(item => {
            if (!item.isOldList) {
              item.id = null
            }
          })
          if (this.tableData.filter(item => !item.useNumber).length > 0) {
            this.$message.warning('使用数量不能为空')
            return
          } else if (this.tableData.filter(item => item.useNumber && !this.SETTINGS.reg_no_zero.test(item.useNumber)).length) {
            this.$message.warning('使用数量未正确填写')
            return
          } else if (this.tableData.filter(item => item.useNumber && Number(item.useNumber) > Number(item.inventoryNumber)).length > 0) {
            this.$message.warning('使用数量不能大于库存数量')
            return
          }
          this.formData.data = this.tableData
          this.formData.status = 4
          this.formData.isSubmit = 0
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.isSubmit = this.isSubmit
          this.formData.id = this.id
          this.formData.roleIds = this.formData.roleIdsArray
          this.tableData.forEach(item => {
            if (!item.isOldList) {
              item.id = null
            }
          })
          if (this.tableData.filter(item => !item.useNumber).length > 0) {
            this.$message.warning('使用数量不能为空')
            return
          } else if (this.tableData.filter(item => item.useNumber && !this.SETTINGS.reg_no_zero.test(item.useNumber)).length) {
            this.$message.warning('使用数量未正确填写')
            return
          } else if (this.tableData.filter(item => item.useNumber && Number(item.useNumber) > Number(item.inventoryNumber)).length > 0) {
            this.$message.warning('使用数量不能大于库存数量')
            return
          }

          this.formData.data = this.tableData
          this.formData.isSubmit = 1
          this.formData.status = 3
          // if (this.formData.repairOption == 0) {
          //   this.formData.firmName = undefined
          //   this.formData.firmId = ''
          // }
          if (this.isEdit) {
            this.formData.completeTime = moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        if (res.data) {
          this.tableData = []
          res.data.forEach(item => {
            item.batchInventoryId = item.batchId
            if (Number(item.number) > Number(item.batchInventoryNumber)) {
              this.$message.warning('导入的数据中存在出库数量大于库存数量的数据,请修改后重新导入')
              return false
            } else {
              this.tableData.push(item)
            }
          })
        }
      })
    },
    addType() { // 打开故障类型详情弹窗
      this.$layer.iframe({// 弹框
        content: {
          content: addErrorType, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            typeId: this.formData.typeId ? this.formData.typeId : ''
          }// props
        },
        area: ['700px', '492px'],
        title: '请选择故障类型', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择物料后从弹窗取出来的数据
    addMaterial(data) {
      this.tableData = data
    },
    maintainType(value) {
      // var obj = {}
      // obj = this.repairOption.find(item => {
      //   return item.id == value
      // })
      // this.nativeSelect = obj.id
      // if (this.nativeSelect !== '0') {
      //   this.formData.repairOption = '1'
      //   this.disabled = false
      // } else {
      //   this.formData.repairOption = '0'
      //   this.disabled = true
      //   this.formData.firmId = ''
      //   this.formData.firmName = undefined
      //   this.formData.cost = undefined
      // }
    },
    addRecord() { // 打开选择备件
      this.$layer.iframe({// 弹框
        content: {
          content: addRecord, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            defaultValue: {
              parentId: 0,
              parentName: '根目录'
            },
            selectedRow: this.tableData
          }// props
        },
        area: ['1320px', '700px'],
        title: '选择备件信息', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    removeRow(row) { // 删除行
      this.tableData.splice(this.tableData.indexOf(row), 1)
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
    },
    addErrorType(row) { // 设备类型弹窗关闭后赋值
      this.getList()
      this.formData.typeId = row.id
      this.formData.malfunctionTypeName = row.name
      this.getList()
    },
    setFileName2(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    }
  }
}
</script>

<style lang="less" scoped>
.table_container{
  padding-bottom: 20px;
}
/deep/.el-input__count {
  bottom: 1px !important;
}
.main_main{
  padding-top:0;
  .formItem_header{
    justify-content: flex-end;
    align-items: flex-start;
    height: 40px;
  }
}
.main_main_third{
  /deep/ .el-form-item__label{
    width: 140px !important;
  }
  /deep/ .el-form-item__content{
    width: calc(100% - 140px) !important;
  }
}
/deep/ .el-tab-pane{
  overflow-y: overlay;
}
</style>
